<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :width="width" :title="getTitle" destroyOnClose @ok="handleSubmit">
    <BasicForm @register="registerForm" class="menuForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from "vue"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { formSchema, ComponentTypes } from "./data"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { list, saveOrUpdateMenu } from "./api"
  import * as resourceApi from "/@/api/iam/resource"
  import { useAdapt } from "/@/hooks/system/useAutoAdapt"
  import { useMessage } from "/@/hooks/web/useMessage"
  const { createMessage } = useMessage()
  // 声明Emits
  const emit = defineEmits(["success", "register"])
  const { width } = useAdapt({ xl: 700, lg: 700, md: 700, sm: 700, xs: 700 })
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const menuType = ref("0")
  const appId = ref("")
  const isLink = (type) => type === "link_page" || type === "link_group"

  const [registerForm, { setProps, resetFields, setFieldsValue, updateSchema, validate, clearValidate, getFieldsValue }] = useForm({
    labelWidth: 100,
    wrapperCol: {
      xs: { span: 20 },
      sm: { span: 20 },
    },
    schemas: formSchema,
    showActionButtonGroup: false,
  })

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields()
    setDrawerProps({ confirmLoading: false })
    isUpdate.value = !!data?.isUpdate
    appId.value = data.appId
    menuType.value = data?.record?.menuType
    updateSchema([
      {
        field: "parentId",
        componentProps: {
          api: list,
          immediate: true,
          params: {},
          onSelect: (value: any, option: any) => {
            // setFieldsValue({name})
            // setDrawerProps({loading:false});
          },
        },
      },
      {
        field: "pageUrl",
        required: isLink(data.record?.type),
      },
    ])

    if (typeof data.record === "object") {
      let values = { ...data.record }
      setFieldsValue(values)
    }

    clearValidate()
    setProps({ disabled: !attrs.showFooter })
  })

  const getTitle = computed(() => (!unref(isUpdate) ? "新增链接" : "编辑链接"))

  async function handleSubmit() {
    try {
      const values = await validate()
      console.log("submit menu: ", values)

      // 去掉 values.component开头的/
      if (values.component && values.component.indexOf("/") == 0) {
        values.component = values.component.slice(1)
      }

      // iframe兼容
      if (ComponentTypes.IFrame === values.component) {
        values.component = values.frameSrc
      }

      if (isUpdate.value && values.parentId === values.id) {
        createMessage.error("上级分类不能选择自己")
        return
      }

      setDrawerProps({ confirmLoading: true })
      await saveOrUpdateMenu({ ...values }, unref(isUpdate))
      closeDrawer()
      createMessage.success(`${getTitle.value}成功`)
      emit("success")
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
